package com.itserver.service.sys.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itserver.mapper.OperateLogMapper;
import com.itserver.pojo.OperateLog;
import com.itserver.pojo.PageResult;
import com.itserver.pojo.QueryLog;
import com.itserver.service.sys.LogService;
import com.itserver.utils.Ip2Region;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class LogServiceImpl implements LogService {
    @Autowired
    private OperateLogMapper operateLogMapper;

    @Override
    public PageResult<OperateLog> logList(QueryLog queryLog) {
        PageHelper.startPage(queryLog.getPage(), queryLog.getPageSize());
        List<OperateLog> rows = operateLogMapper.logList(queryLog);
        // 循环设置ip地址
        rows.forEach(operateLog -> {
            String localIp = "";
            String ip = operateLog.getIp();
            try {
                localIp = Ip2Region.getCity(ip);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            //中国|0|北京|北京市|联通  只提取市级
            if(localIp!=null && !localIp.isEmpty()){
                String[] citys = localIp.split("\\|");
                String city = citys[3];
                if (city!=null){
                    operateLog.setIp(ip+" ( "+ city+" )");
                }
            }else {
                operateLog.setIp(ip);
            }

        });
        Page<OperateLog> page = (Page<OperateLog>) rows;
        return new PageResult<>(page.getTotal(), page.getResult());
    }
    @Override
    public void deleteLog(Integer[] ids) {
        operateLogMapper.deleteLog(ids);
    }
}
